﻿using System;
using System.Windows.Forms;

namespace EncodingTools {
    public partial class StringEncodingControl : UserControl {
        public StringEncodingControl() {
            InitializeComponent();

            _encodingTypes.Items.Add(new EncoderItem("Base-64", new Base64Encoder()));
            _encodingTypes.Items.Add(new EncoderItem("HTML", new HtmlEncoder()));
            _encodingTypes.Items.Add(new EncoderItem("MD5", new Md5Encoder()));
            _encodingTypes.Items.Add(new EncoderItem("SHA-1", new Sha1Encoder()));
            _encodingTypes.Items.Add(new EncoderItem("URL", new UrlEncoder()));
            _encodingTypes.SelectedIndex = 0;
        }

        private EncoderItem SelectedEncoderItem {
            get { return (EncoderItem)_encodingTypes.SelectedItem; }
        }

        private void _encode_Click(object sender, EventArgs e) {
            if (SelectedEncoderItem.EncoderDecoder is IEncoder) {
                byte[] ret = ((IEncoder)SelectedEncoderItem.EncoderDecoder).Encode(_source.Data);
                _output.Data = ret;
            } else {
                _output.Text = "Does not support encoding.";
            }
        }

        private void _decode_Click(object sender, EventArgs e) {
            if (SelectedEncoderItem.EncoderDecoder is IDecoder) {
                byte[] ret = ((IDecoder)SelectedEncoderItem.EncoderDecoder).Decode(_source.Data);
                _output.Data = ret;
            } else {
                _output.Text = "Does not support decoding.";
            }
        }

        public class EncoderItem {
            public string Name { private get; set; }
            public object EncoderDecoder { private set; get; }

            public EncoderItem(string name, object encoderDecoder) {
                Name = name;
                EncoderDecoder = encoderDecoder;
            }

            public override string ToString() {
                return Name;
            }
        }

        private void _encodingTypes_SelectedIndexChanged(object sender, EventArgs e) {
            _decode.Enabled = SelectedEncoderItem.EncoderDecoder is IDecoder;
            _encode.Enabled = SelectedEncoderItem.EncoderDecoder is IEncoder;
        }
    }
}
